import datetime
import psutil
import time
import socket
import json

from threading import Timer

# 目标IP地址和端口
target_ip = "192.168.199.178"
target_port = 60000

cpu_percent = 0.0
memory_percent = 0.0
percent = 0.0
upsp = 0.0
downsp = 0.0

download_glod = 0

upload_glod = 0

sorted_data_glod = []


def time_printer():
    now = datetime.datetime.now()
    ts = now.strftime('%Y-%m-%d %H:%M:%S')
    print('do func time :', ts)
    print_network_speed()
    loop_monitor()

def loop_monitor():
    t = Timer(1, time_printer)
    t.start()

def print_system_stats(interval=1):
    global cpu_percent
    global memory_percent
    global percent
    cpu_percent = psutil.cpu_percent(interval=interval, percpu=False)
    memory_percent = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/')
    percent = disk_usage.percent
    print(f"CPU使用率: {cpu_percent}%")
    print(f"内存使用率: {memory_percent}%")
    print(f"硬盘使用情况: {disk_usage.percent}%")


def get_network_speed():
    net_io_counters = psutil.net_io_counters(pernic=True)
    nic_names = net_io_counters.keys()
    for nic_name in nic_names:
        net_io = net_io_counters[nic_name]
        if nic_name.startswith('WLAN'):
            download_speed = net_io.bytes_recv
            upload_speed = net_io.bytes_sent
    return download_speed, upload_speed


def print_network_speed():
    global upsp
    global downsp
    global download_glod
    global upload_glod
    download_speed, upload_speed = get_network_speed()
    downsp= (download_speed - download_glod) * 8 / 1024
    upsp = (upload_speed - upload_glod) * 8 / 1024
    upload_glod = upload_speed
    download_glod = download_speed
    print(f'下行速率: {upsp:.2f} kbps, 上行速率 {downsp:.2f} kbps')


def sendDataByUDP():
    data = {
        "type": 1,
        "cpu": cpu_percent,
        "ram": memory_percent,
        "rom": percent,
        "upsp": '{:.2f}'.format(upsp),
        "downsp": '{:.2f}'.format(downsp)
    }
    # byte_array = bytearray(0xff,0xff,0xff,0xff)
    json_data = json.dumps(data).encode('utf-8')  # 将JSON数据编码为字节串
    # 创建UDP数据包
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # 创建UDP socket对象
    # sock.settimeout(1)  # 设置超时时间，以秒为单位
    try:
        sock.sendto(json_data, (target_ip, target_port))  # 发送UDP数据包
    except Exception as e:
        print(f"发送UDP数据包时发生错误：{e}")
    finally:
        sock.close()  # 关闭socket连接

def sendPidDataByUDP():
    data = {
        "type": 2,
        "pid": sorted_data_glod
    }
    json_data = json.dumps(data).encode('utf-8')  # 将JSON数据编码为字节串
    # 创建UDP数据包
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # 创建UDP socket对象
    # sock.settimeout(1)  # 设置超时时间，以秒为单位
    try:
        sock.sendto(json_data, (target_ip, target_port))  # 发送UDP数据包
    except Exception as e:
        print(f"发送UDP数据包时发生错误：{e}")
    finally:
        sock.close()  # 关闭socket连接

def getSoftwordPid():
    for proc in psutil.process_iter():
        try:
            # Get process name & pid from process object.
            processName = proc.name()
            processID = proc.pid
            print(processName , ' ::: ', processID)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

def getSoftwordPidList():
    global sorted_data_glod
    listOfProcessNames = list()
    for proc in psutil.process_iter():
        pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])
        # Append dict of process detail in list
        if((pInfoDict['cpu_percent']>0) and (pInfoDict["name"] != 'System Idle Process')):
          listOfProcessNames.append(pInfoDict)
    sorted_data = sorted(listOfProcessNames, key=sort_by_cpu_percent,reverse=True)
    sorted_data_glod = sorted_data[:4]
    print(sorted_data_glod)

#排序函数
def sort_by_cpu_percent(item):
    return item["cpu_percent"]



if __name__ == '__main__':
    loop_monitor()
    while True:
        print_system_stats(interval=1)
        sendDataByUDP()
        # getSoftwordPid()
        getSoftwordPidList()
        sendPidDataByUDP()

